package com.plian.system.service.nkgl.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.im.BaseInvestmentExecution;
import com.plian.system.entity.ms.DailyThing;
import com.plian.system.entity.nkgl.InternalManagement;
import com.plian.system.mapper.ms.DailyThingMapper;
import com.plian.system.mapper.nkgl.InternalManagementMapper;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.service.ms.IDailyThingService;
import com.plian.system.service.nkgl.IInternalManagementService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.ms.DailyThingVO;
import com.plian.system.vo.nkgl.InternalManagementVO;
import com.plian.system.wrapper.ms.DailyThingWrapper;
import com.plian.system.wrapper.nkgl.InternalManagementWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 月度计划表 服务实现类
 *
 * @author xiaohu
 */
@Slf4j
@Service
@AllArgsConstructor
public class InternalManagementServiceImpl extends BaseServiceImpl<InternalManagementMapper, InternalManagement> implements IInternalManagementService, BaseFlowService {

	private FormWorkflowService formWorkflowService;

	private IFormCodeService formCodeService;

	private FileService fileService;

	private InternalManagementWrapper internalManagementWrapper;

	@Override
	public HashMap<String,Object> commit(String id) {
		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
		//将需要提交的流程变量返回，用于工作流侧
		return new HashMap<String,Object>();
	}

	@Override
	public Boolean finish(String id) {
		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
	}

	@Override
	public Boolean reject(String id, int formState, String comment) {
		return handleStatus(Long.valueOf(id), formState);
	}

	@Override
	public Boolean checkIsExisted(Long id, String code) {
		if (Optional.ofNullable(code).isPresent()) {
			InternalManagement internalManagement = new InternalManagement();
			internalManagement.setCode(code);
			if (Optional.ofNullable(getOne(Condition.getQueryWrapper(internalManagement))).isPresent()) {
				if (id == null || !id.equals(getOne(Condition.getQueryWrapper(internalManagement)).getId())) {
					return false;
				}
			}
		}
		return true;
	}

	@Override
	public boolean saveOrUpdate(InternalManagement internalManagement) {

		if (!Optional.ofNullable(internalManagement.getStatus()).isPresent()) {
			internalManagement.setStatus(FormStatusConstant.UNREVIEWED);
		}
		if (!Optional.ofNullable(internalManagement.getId()).isPresent()) {
			internalManagement.setCode(formCodeService.getCode(FormTypeConstant.INTERNAL_MANAGEMENT));
			internalManagement.setFormType(String.valueOf(FormTypeConstant.INTERNAL_MANAGEMENT));
		}
		return super.saveOrUpdate(internalManagement);
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public Boolean submit(InternalManagement internalManagement) {
		boolean result = saveOrUpdate(internalManagement);
		fileService.saveAll(String.valueOf(internalManagement.getId()), internalManagement.getDocList());
		return result;

	}
	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public Boolean edit(InternalManagement internalManagement) {
		boolean result = super.saveOrUpdate(internalManagement);
		fileService.edit(String.valueOf(internalManagement.getId()), internalManagement.getDocList());
		return result;
	}
	@Override
	public Boolean checkCancel(Long id) {
		InternalManagement internalManagement = getById(id);
		if (!Optional.ofNullable(internalManagement).isPresent()) {
			return false;
		}
		return true;
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean deleteLogic(List<Long> ids) {
		for (Long id : ids) {
			InternalManagement internalManagement = getById(id);
			if (internalManagement == null) {
				return false;
			} else if (internalManagement.getStatus() != null &&
					(internalManagement.getStatus() != FormStatusConstant.STASH && internalManagement.getStatus() != FormStatusConstant.UNREVIEWED)) {
				return false;
			}
			formWorkflowService.deleteProcessInstance(String.valueOf(id));
		}

		return super.deleteLogic(ids);
	}

	/**
	 * 统一处理状态机事件方法
	 *
	 * @param id          主键
	 * @param updateStatus 更新状态
	 * @return boolean
	 */
	private Boolean handleStatus(Long id, int updateStatus) {
		try {
			InternalManagement internalManagement = getById(id);
			/**
			 * 设置审批人和审批时间
			 */
			if (updateStatus == FormStatusConstant.FINISH){
				internalManagement.setApprovedUser(TokenUtil.getTokenUserId());
				Date now = DateUtil.now();
				internalManagement.setApprovedTime(now);
			}
			internalManagement.setStatus(updateStatus);
			updateById(internalManagement);
			return true;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return false;
		}
	}

	@Override
	public List<PageData> findByIds(List<String> formIds) {
		LambdaQueryWrapper<InternalManagement> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(InternalManagement::getId, Func.toLongList(org.apache.commons.lang3.StringUtils.join(formIds, StringPool.COMMA)));
		List<InternalManagement> internalManagements = list(queryWrapper);
		List<InternalManagementVO> internalManagementVOS = internalManagementWrapper.entityToVO(internalManagements);
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(internalManagementVOS)){
				for (InternalManagementVO vo : internalManagementVOS){
					PageData pd = new PageData();
					pd.put("id", vo.getId());
					pd.put("UNITNAME", vo.getFillCompanyName());
					pd.put("APPLICANTNAME", vo.getCreateUserName());
					pd.put("applicantId", vo.getCreateUser());
					pd.put("applyOrganizationId", vo.getFillCompanyId());
					pd.put("formType", FormTypeConstant.INTERNAL_MANAGEMENT);
					pd.put("orgName", vo.getFillCompanyName());
					pageDataList.add(pd);
				}
			}
			return pageDataList;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		return pageDataList;
	}

	@Override
	public List<Integer> getFormType() {
		return Arrays.asList(FormTypeConstant.INTERNAL_MANAGEMENT);
	}

	@Override
	public void goBackToStash(String formId) {
		handleStatus(Long.valueOf(formId), UNREVIEWED);
	}





}
